setwd("C:/Users/tim/Documents/Distance Covariance Project/distancecovariance/R Code/")
#setwd("C:/Documents and Settings/ORIE user1/My Documents/Distance Covariance Project/R Code/")
#setwd("C:/Documents and Settings/1083117/My Documents/Distance Covariance Project/R Code")
#optional to get the analysis running...
source("Functions/source.all.R")
source.all() #this will produce errors if there are any uninstalled packages
install.all.packages() #install any missing packages
source.all() #source again...

###################################

n=100
M=100
alpha = .05
nus = seq(1,51,5)	

dcov.power = NULL
cor.power = NULL
dcov.test.stats=NULL
cor.test.stats=NULL
for (nu in nus){
	cor.dcov.power.study.trial.result=NULL
	dcov.passed.aggregate =0
	cor.passed.aggregate = 0
	dcov.test.stat = NULL
	cor.test.stat  = NULL
	#progress...
	print(nu)
	for(N in 1:M){
		
		cor.dcov.power.study.trial.result = cor.dcov.power.study.trial.chisq(nu,n)		
		dcov.passed.aggregate = ifelse(cor.dcov.power.study.trial.result$dcov.pvalue < alpha,dcov.passed.aggregate+1,dcov.passed.aggregate);
		cor.passed.aggregate = ifelse(cor.dcov.power.study.trial.result$cor.pvalue < alpha,cor.passed.aggregate+1,cor.passed.aggregate);
		dcov.test.stat = c(dcov.test.stat,cor.dcov.power.study.trial.result$dcov.teststat)
		cor.test.stat = c(cor.test.stat, cor.dcov.power.study.trial.result$cor.teststat)
		#progress...	
		print(N/M)

	}	
	dcov.power = c(dcov.power,dcov.passed.aggregate / M)
	cor.power = c(cor.power,cor.passed.aggregate / M)
	dcov.test.stats=cbind(dcov.test.stats,dcov.test.stat)
	cor.test.stats = cbind(cor.test.stats,cor.test.stat)
	
	
}
test.data.vector = as.data.frame(cbind(dcov.power,cor.power))
names(test.data.vector)=c("Distance Covariance Test Power","Pearson Correlation Test Power")
y = stack(test.data.vector)
x = seq(1,dim(test.data.vector)[1])
x_all=rep(x,length(test.data.vector))
dev.new()	
plot.new()

p=myoverplot(y[,1] ~ x_all | y[,2], dates = nus,data = test.data.vector, xlab="v",ylab="", main=paste("Distance Covariance vs. Pearson Correlation"), plot = T,f=0,same.scale=T)

#dcov test stats
dcov.test.stats.df = as.data.frame(dcov.test.stats)
names(dcov.test.stats.df) = nus
dcov.test.stat.density = density(dcov.test.stats[,1])
dev.new()
plot(dcov.test.stat.density,main="Distance Covariance Test Stat Density Estmiate")
sink(file="dcov.test.stats.csv")
dcov.test.stats.df
sink()

#cor test stats
cor.test.stats.df = as.data.frame(cor.test.stats )
cor.test.stat.density = density(cor.test.stats[,1])
dev.new()
plot(cor.test.stat.density,main="Pearson Correlation Test Stat Density Estmiate")
names(cor.test.stats.df)=nus
sink(file="cor.test.stats.csv")
cor.test.stats.df
sink()


